import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtButton, AtForm,AtInput } from 'taro-ui'

import './bindPhone.scss'
import {api_phone_exist} from '../../../utils/api.jsx'
import {api_bind_phone} from '../../../utils/api.jsx'
import {api_sms} from '../../../utils/api.jsx'

export default class BindPhone extends Component {

  constructor(props){
    super(props);
    this.state = {
        phone:'',  //手机号
        password:'',  //密码
        re_password:'', //再次密码
        code:'',  //验证码
        count: 60,  //验证码计时
        code_text: '发送验证码',   // 按钮文本
        disableBtn: false, //‘发送验证码’按钮是否禁用
    }
  }

  toStrictInfo = () => {
    Taro.navigateTo({url: '/pages/pagesB/strictInfo/strictInfo'})
  }

  countDown = () => {
    let count = this.state.count
    const timer = setInterval(() => {
      this.setState({
        count:(count--),
        disableBtn:true,
        code_text:count + 'S后重发'
      },() => {
        if(count == 0){
          clearInterval(timer)
          this.setState({
            disableBtn:false,
            count: 60,
            code_text:'发送验证码'
          })
        }
      })
    },1000)
  }

  // 用户点击发送验证码时检查手机号
  verifyPhoneExist = async () => {
    const params = {
      url: api_phone_exist,
      data: {
        phone:this.state.phone,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('isPhoneExist',res.data)},
      fail: (res) => {console.log(res.data)}
    }
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
    if (!myreg.test(this.state.phone)) {
      // 手机号格式错误时，直接返回，不会发送数据
      if(this.state.phone.length == 0){
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
        return false
      }else{
        Taro.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 2000
        })
      }      
      return false
    }else{
      await Taro.request(params)
      const isPhoneExist = Taro.getStorageSync('isPhoneExist')
      if(isPhoneExist){
        Taro.showModal({
          title: 'Tip',
          cancelText:'取消',
          confirmText:'确认',
          content: '您的手机号已注册!前往登录',
          success: function (res) {
            if (res.confirm) {
              Taro.navigateTo({url: '/pages/pagesB/login/login'})
            } else if (res.cancel) {
              
            }
          }
        })
        return
      }else{
        const params_2 = {
          url: api_sms,
          data: {
            phone:this.state.phone,
            flag:0
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: (res) => {Taro.setStorageSync('smsFlag',res.data)},
          fail: (res) => {console.log(res.data)}
        }
        await Taro.request(params_2)
        const smsFlag = Taro.getStorageSync('smsFlag')
        if(smsFlag){
          Taro.showToast({
            title: '验证码已发送',
            icon: 'none',
            duration: 2000
          })
          this.countDown()
        }
        return true
      }
    }
  }

  // 两次密码必须一致
  checkPwd = () => {
    if(this.state.password.length == 0){
      Taro.showToast({
        title: '请填写密码',
        icon: 'none',
        duration: 2000
      })
    }else if(this.state.password.length < 6){
      Taro.showToast({
        title: '密码长度必须不小于6',
        icon: 'none',
        duration: 2000
      })
    }else if(this.state.password != this.state.re_password){
      Taro.showToast({
        title: '两次密码必须一致',
        icon: 'none',
        duration: 2000
      })
    }else{
      return true
    }
  }

  // 用户点击确定时再次验证
  checkCorrect = async () => {
    const params = {
      url: api_bind_phone,
      cache:'reload',
      data: {
        phone:this.state.phone,
        code:this.state.code,
        password:this.state.password
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: (res) => {Taro.setStorageSync('key',res.data)},
      fail: (res) => {console.log(res.data)}
    }

    // 当手机号和密码验证无误后才发送请求
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
    if(!myreg.test(this.state.phone)){
      if(this.state.phone.length == 0){
        Taro.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 2000
        })
        return false
      }else{
        Taro.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 2000
        })
      }
      return false
    }else if(this.state.code.length == 0){
      Taro.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return false
    }else if(this.state.password.length == 0){
      Taro.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return false
    }else if(this.state.password != this.state.re_password){
      Taro.showToast({
        title: '两次密码必须一致',
        icon: 'none',
        duration: 2000
      })
      return false
    }else{
      // 输入没有问题才会发送请求
      await Taro.request(params)
      const result = Taro.getStorageSync('key')
      if(result){
        Taro.showToast({
          title: '注册成功',
          icon: 'success',
          duration: 1000
        })

        // 绑定成功后设置缓存，记录其登录状态
        Taro.setStorage({
          key:"userInfo",
          data:{
            userPhone:this.state.phone,
            isLogin:true
          }
        })
        
        // 设置缓存，以分辨用户进入身份信息填写页面是是刚注册还是刚登录
        Taro.setStorage({
          key:"bindFlag",
          data:{
            bindFlag:true
          }
        })
        setTimeout(this.toStrictInfo,1000)
      }else{
        Taro.showToast({
          title: '验证码错误',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }

  render () {
    return (
      <View>
        <AtForm>
          <AtInput className='phone'
            name='phone'
            border={true}
            title=''
            type='phone'
            placeholder='请输入手机号码'
            value={this.state.phone}
            onChange={(e) =>this.setState({phone:e})}
          >
          </AtInput>

          <AtInput className='code'
            name='code'
            border={true}
            title=''
            type='number'
            placeholder='请输入验证码'
            value={this.state.code}
            onChange={(e) =>this.setState({code:e})}
          >
            <AtButton className='codeBtn' size='small' disabled={this.state.disableBtn} onClick={this.verifyPhoneExist}>{this.state.code_text}</AtButton>
          </AtInput>

          <AtInput className='password'
            name='password'
            border={true}
            title=''
            type='password'
            placeholder='请输入密码'
            value={this.state.password}
            onChange={(e) =>this.setState({password:e})}
          >
          </AtInput>

          <AtInput className='re_password'
            name='re_password'
            border={true}
            title=''
            selectionStart='50'
            selectionEnd='-1'
            type='password'
            placeholder='请再次输入密码'
            value={this.state.re_password}
            onChange={(e) =>this.setState({re_password:e})}
            onBlur={this.checkPwd}
          >
          </AtInput>
          <button className='verifyBtn' type='primary' onClick={this.checkCorrect}>确定</button>
        </AtForm>

        {/* 引导登录 */}
        <view className='tip'>
          已有账号？
          <text className='tipLog' onClick={() =>Taro.navigateTo({url: '/pages/pagesB/login/login'})}>前去登录&gt;&gt;&gt;
          </text>
        </view>
      </View>
    )
  }
}